<template>
  <a-modal
    :title="title"
    :width="800"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleOk"
    :bodyStyle="bodyStyle"
    @cancel="handleCancel"
    cancelText="关闭"
    wrapClassName="ant-modal-cust-warp"
    style="top:15%;height: 70%;overflow-y: hidden"
  >
    <template slot="footer">
      <a-button key="back" v-if="isReadOnly" @click="handleCancel">
        关闭
      </a-button>
    </template>
    <a-spin :spinning="confirmLoading">
      <a-form :form="form" id="customerModal">
        <a-col :span="12">
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="审批流程ID">
            <a-input disabled v-decorator.trim="['approvalId']" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="上传图纸">
            <div :key="Math.random()">
              <a-upload
                name="file"
                accept="image/png,image/jpeg,image/webp,image/jpg,.doc,.docx,.pdf"
                :beforeUpload="beforeUpload"
                :showUploadList="false"
                :multiple="false"
                :headers="tokenHeader"
                :action="importExcelUrl"
                @change="myhandleImportExcel"
              >
                <a-button><a-icon type="upload" />上传</a-button>
              </a-upload>
            </div>
          </a-form-item>
        </a-col>
      </a-form>
    </a-spin>
  </a-modal>
</template>
<script>
import pick from 'lodash.pick'
import { checkSupplier, toUpload } from '@/api/api'
import Vue from 'vue'
import { autoJumpNextInput } from '@/utils/util'
import { ACCESS_TOKEN } from '@/store/mutation-types'
export default {
  name: 'ToUpload',
  data() {
    return {
      title: '操作',
      tokenHeader: { Authorization: 'Bearer ' + Vue.ls.get(ACCESS_TOKEN) },
      bodyStyle: {
        padding: '20',
        height: window.innerHeight * 0.5 + 'px',
        'overflow-y': 'auto'
      },
      defaultFileList: null,
      url: {
        importExcelUrl: '/systemConfig/upload' + '?' + `biz=sptz`
      },
      visible: false,
      model: {},
      record: null,
      isReadOnly: false,
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      confirmLoading: false,
      form: this.$form.createForm(this),
      validatorRules: {
        name: {
          rules: [
            { required: true, message: '请输入名称!' },
            { min: 2, max: 30, message: '长度在 2 到 30 个字符', trigger: 'blur' },
            { validator: this.validateSupplierName }
          ]
        }
      }
    }
  },
  created() {},
  computed: {
    importExcelUrl: function() {
      return `${window._CONFIG['domianURL']}${this.url.importExcelUrl}`
      // return `api${this.url.importExcelUrl}`
    }
  },
  methods: {
    //图片上传前做限制
    beforeUpload(file) {
      console.log(file)
      return new Promise((resolve, reject) => {
        // let isType =
        //   file.type === 'image/jpg' ||
        //   file.type === 'image/jpeg' ||
        //   file.type === 'image/png' ||
        //   file.type === 'image/webp' ||
        //   file.type === 'doc' ||
        //   file.type === 'docx' ||
        //   file.type === 'pdf'
        // if (!isType) {
        //   this.$message.error('格式错误,只能上传jpg、jpeg、png、webp、doc、docx、pdf')
        //   return reject(false)
        // }
        return resolve(true)
      })
    },
    add() {
      this.edit()
    },
    edit(record) {
      this.form.resetFields()
      this.model = Object.assign({}, record)
      this.defaultFileList = this.model.contractFile
      this.visible = true
      console.log(this.model)
      this.$nextTick(() => {
        this.form.setFieldsValue({ approvalId: this.model.id })
        this.form.setFieldsValue(pick(this.model))
        autoJumpNextInput('customerModal')
      })
    },
    close() {
      this.$emit('close')
      this.visible = false
    },
    /* 导入 */
    myhandleImportExcel(info) {
      if (info.file.status !== 'uploading') {
        console.log(info.file, info.fileList)
      }
      if (info.file.status === 'done') {
        if (info.file.response) {
          // this.$message.success(`${info.file.name} 文件上传成功`);
          if (info.file.response.code === 200 || info.file.response.code === 10000) {
            this.$message.success(`${info.file.name} 文件上传成功` || info.file.response.data)
            this.defaultFileList = info.file.response.data
          } else {
            this.$message.warning(info.file.response.message)
          }
        } else {
          this.$message.error(`${info.file.name} ${info.file.response.data}.`)
        }
      } else if (info.file.status === 'error') {
        this.$message.error(`文件上传失败: ${info.file.msg} `)
      }
    },
    handleOk() {
      const that = this
      // 触发表单验证
      this.form.validateFields((err, values) => {
        if (!err) {
          that.confirmLoading = true
          let formData = Object.assign(values)
          let obj
          formData.bluePrintUrl = this.defaultFileList
          if (this.model.id) {
            obj = toUpload(formData)
          }
          obj
            .then(res => {
              if (res.code === 200 || res.code === 10000) {
                that.$message.success(res.message)
                that.$emit('ok')
              } else {
                that.$message.warning(res.data)
              }
            })
            .finally(() => {
              that.confirmLoading = false
              that.close()
            })
        }
      })
    },
    handleCancel() {
      this.close()
    },
    validateSupplierName(rule, value, callback) {
      let params = {
        name: value,
        type: '客户',
        id: this.model.id ? this.model.id : 0
      }
      checkSupplier(params).then(res => {
        if (res && res.code === 200) {
          if (!res.data.status) {
            callback()
          } else {
            callback('名称已经存在')
          }
        } else {
          callback(res.data)
        }
      })
    }
  }
}
</script>
<style scoped>
@import '~@assets/less/common.less';
</style>
